package cn.lijigou.shopping.alipay;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import cn.lijigou.shopping.AlipayCardActivity;
import cn.lijigou.shopping.CompleteOrderActivity;
import cn.lijigou.shopping.ConfirmOrderActivity;
import cn.lijigou.shopping.HomeActivity;
import cn.lijigou.shopping.LoginActivity;
import cn.lijigou.shopping.OrderApprobateActivity;
import cn.lijigou.shopping.OrdersActivity;
import cn.lijigou.shopping.R;
import cn.lijigou.shopping.ShopDetailActivity;
import cn.lijigou.shopping.domain.MRsa;
import cn.lijigou.shopping.domain.Order;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.service.ServerService;
public class Alipay {
	private ProgressDialog mProgress = null;
	private Activity activity = null;
	private TextView payTip = null;
	private  MRsa mRsa = null;
	private  String info = ""; 
	
	private String session = "";
	private String uid = "";
	private String mobile = "";
	private String receiver_name = "";
	private String receiver_address = "";
	private String leave_msg = "";
	private String order_id = "";
	private String shop_id = "";
	private String shopTitle = "";
	private String mCouponCode = "";
	
	private String size = "1";
	private boolean isDummy = true;
	private Dialog mDialog = null;
	private Button mMyOrder = null;
	private Button mCancle = null;
	
	//	首次支付
	public Alipay(Activity activity, String shopId, String size ,String mobile, String shopTitle, String receiver_name, String receiver_address, String leave_msg
			,String mCouponCode) {
		super();
		this.activity = activity;
		this.shop_id = shopId;
		this.size = size;
		this. mobile = mobile;
		this.isDummy = MSystem.isLoginDummy(activity);
		this.session  = MSystem.session;
		this.uid =MSystem.uid;
		this.shopTitle = shopTitle;
		this.receiver_name = receiver_name;
		this.receiver_address = receiver_address;
		this.leave_msg = leave_msg;
		this.mCouponCode = mCouponCode;
	}
	//	重复支付
	public Alipay(Activity activity,String orderId , String shopTitle) {
		super();
		this.activity = activity;
		this.order_id  = orderId;
		this.isDummy = MSystem.isLoginDummy(activity);
		this.session  = MSystem.session;
		this.uid =MSystem.uid;
		this.shopTitle = shopTitle;
	}
	
	public  void alipayCard() {
		if(!"".equals(order_id)){// 二次支付
			String url_info = MSystem.alipay_card_again(uid,order_id);
			Intent intent = new Intent(activity, AlipayCardActivity.class);
			intent.putExtra("url_info", url_info);
			intent.putExtra("shopTitle", shopTitle);
			activity.startActivity(intent);
		}else{
			String url_info = MSystem.alipay_card_first(uid,shop_id,size,mobile,receiver_name,receiver_address,leave_msg,mCouponCode);
			Intent intent = new Intent(activity, AlipayCardActivity.class);
			intent.putExtra("url_info", url_info);
			intent.putExtra("shopTitle", shopTitle);
			activity.startActivity(intent);
		}
		
	}
	public  void alipay() {
		
		if("".equals(order_id) && ConfirmOrderActivity.mDialog.isShowing()){
			ConfirmOrderActivity.mDialog.dismiss();
		}
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(activity);
		boolean isMobile_spExist = mspHelper.detectMobile_sp();
		if (!isMobile_spExist)
			return;
		try {
			// prepare the order info.
			
				if(!"".equals(order_id)){		// 二次支付
					if("".equals(info)){//防止重复订单
						info = ServerService.agian_pay(uid, session, order_id).getInfo();
					}
				}else{
					if(mRsa==null){//防止重复订单
						mRsa = ServerService.first_pay(uid, session, shop_id, size, mobile,receiver_name,receiver_address,leave_msg,mCouponCode);//首次支付
						if(mRsa!=null){
							//保存虚拟账号
							SharedPreferences sp = activity.getSharedPreferences("user", Context.MODE_PRIVATE);
							Editor edit = sp.edit();
							edit.putString("uid",mRsa.getUser_id());
							edit.putString("session",mRsa.getSession());
							edit.putString("isTmp", mRsa.getIsTmp());
							edit.commit();
							info = mRsa.getInfo();
					}
				}
			}

			// start the pay.
			MobileSecurePayer msp = new MobileSecurePayer();
			boolean bRet = msp.pay(info, mHandler, AlixId.RQF_PAY, activity);

			if (bRet) {
				// show the progress bar to indicate that we have started
				// paying.
				closeProgress();
				mProgress = BaseHelper.showProgress(activity, null, "正在支付", false,
						true);
			} else
				;
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	private Handler mHandler = new Handler() {
	public void handleMessage(Message msg) {
		try {
			final String strRet = (String) msg.obj;

			switch (msg.what) {
			case AlixId.RQF_PAY: {
				closeProgress();

				BaseHelper.log("ccc", strRet);
				try {
					String memo = "memo=";
					int imemoStart = strRet.indexOf("memo=");
					imemoStart += memo.length();
					int imemoEnd = strRet.indexOf(";result=");
					memo = strRet.substring(imemoStart, imemoEnd);

					String result = "resultStatus=";
					int iresultStart = strRet.indexOf("resultStatus=");
					iresultStart += result.length();
					int iresultEnd = strRet.indexOf(";memo=");
					result = strRet.substring(iresultStart+1, iresultEnd-1);
					if("9000".equals(result)){
							Intent intent = new Intent(activity, CompleteOrderActivity.class);
							intent.putExtra("shopTitle", shopTitle);
							activity.startActivity(intent);
					}
					
					
					ResultChecker resultChecker = new ResultChecker(strRet);

					int retVal = resultChecker.checkSign();
					if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
//						BaseHelper.showDialog(
//								ShopDetailActivity.this,
//								"提示",
//								getResources().getString(
//										R.string.check_sign_failed),
//								android.R.drawable.ic_dialog_alert);
					} else {
//						BaseHelper.showDialog(ShopDetailActivity.this, "提示", memo,
//								R.drawable.infoicon);
					}
				} catch (Exception e) {
					e.printStackTrace();

//					BaseHelper.showDialog(ShopDetailActivity.this, "提示", strRet,
//							R.drawable.infoicon);
				}
			}
				break;
			}

			super.handleMessage(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
};


public void setShadow(Boolean isTransparent){
	WindowManager.LayoutParams lp=activity.getWindow().getAttributes();
	if(isTransparent){
        lp.alpha=0.3f;
        lp.dimAmount=0.3f;
        activity.getWindow().setAttributes(lp);
        activity.getWindow().setAttributes(lp);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
	}else{
		lp.alpha=1.0f;
        lp.dimAmount=1.0f;
        activity.getWindow().setAttributes(lp);
        activity.getWindow().setAttributes(lp);
	}

}

//
// the OnCancelListener for lephone platform.
public static class AlixOnCancelListener implements
		DialogInterface.OnCancelListener {
	Activity mcontext;

	public AlixOnCancelListener(Activity context) {
		mcontext = context;
	}

	public void onCancel(DialogInterface dialog) {
		mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
	}
}

	//
	// close the progress bar
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void setPay(View v1){
		payTip = (TextView) v1.findViewById(R.id.dialog_title);
		payTip.setText("恭喜你购买成功");
	}
}
